<template>
  <div id="main-content" class="sell-box">
    <!-- eslint-disable -->
    <Scroll ref="tabScroll" :scroll-bars="false" scroll-direction="X" class="tab">
      <div slot="body" ref="tabList" class="tab-list">
        <div v-for="(filter, index) in filterList" @click="selectFilter(filter)" :key="index" :class="['tab-item',  filter.status === currentFilterStatus ? 'active' : null]">
          <span>{{filter.name}}</span>
          <span v-if="filter.num > 0" class="badge">{{filter.num}}</span>
        </div>
      </div>
    </Scroll>
    <Scroll class="release-list" v-for="(filter, index) in filterList" :ref="`scroll_${filter.alias}`" v-show="filter.alias === currentFilterStatusAlias" :key="`${index}-${index}`" @infiniteScroll="getMySellList">
      <!-- 循环区域 -->
      <div class="release-item" v-for="(item, i) in currentSellList" :key="i">
        <router-link 
          class="item-tit" 
          tag="div" 
          :to="{path: `/goods/orderDetails/${item.mallSellOrderId}?postage=${item.postage}&sellPrice=${item.sellPrice}&time=${item.orderStatus === 1 ? item.sellTime : (item.endTime || 0)}`}"
        >
          <div class="pic">
            <img class="picItem" :src="item.productsUrl | ImgFilter" alt="IMG">
          </div>
          <div class="goods-info">
            <div class="title">
              <span>{{item.productsName}}</span>
            </div>
            <div class="money">
              <span>￥{{item.sellPrice}}</span>
            </div>
            <div class="state">
              <span>{{item.orderStatus | sellStatusFilter}}</span>
              <!-- eslint-disable -->
              <CountDown 
                :intervalId="`${filter.alias}-${i}`"
                v-if="+item.orderStatus === 1 || +item.orderStatus === 5"
                :totalSeconds="+item.orderStatus === 1 ? item.sellTime : item.sendTime"
                :timeType="item.orderStatus === 5 ? 2 : 1"
                @endTime="handleCountDownEnd(item)"
              >
                <span slot="first" v-if="+item.orderStatus === 1">还剩</span>
                <span v-if="+item.orderStatus === 5">后将自动收货</span>
              </CountDown>
            </div>
          </div>
          <div class="arrow">
            <i class="icon-arrow"></i>
          </div>
        </router-link>
        <div class="edit" v-if="item.orderStatus === 1">
          <button class="edit-btn" @click="handleEdit(item)">编辑价格</button>
          <button class="edit-btn" @click="handleCloseDeal(item)">关闭交易</button>
        </div>
      </div>
      <div class="noList" v-if="emptyList">您暂无卖出的商品<br />去发布一个商品吧！</div>
    </Scroll>
    <Popups :isShow.sync="isPopup_cancel" title="关闭交易">
      <div  class="cancel-info" slot="body">
        <span>关闭交易后买家将无法付款</span>
      </div>
      <div slot="footer" class="pop-footer-btns">
        <button class="pop-footer-cancel" @click="closePopAll" >再想想</button>
        <button class="pop-footer-sub" @click="handleEnsureClose">确定</button>
      </div>
    </Popups>
    <Popups :isShow.sync="isPopup_edit" title="编辑价格">
      <div slot="body">
        <div class="form-item">
          <!-- eslint-disable -->
          <label for="sellPrice" class="form-label">转卖价格</label>
          <input type="number" id="sellPrice" v-model.number="sellPrice" class="form-input" placeholder="请输入转卖价格">
          <span>元</span>
        </div>
      </div>
      <button class="edit-sub" @click="handelSetPrice" slot="footer">确定</button>
    </Popups>
  </div>
</template>

<script>
import { Popups } from "~/popOut/";
import CountDown from "~/countDown";
import { Scroll } from "~/vScroll";
import Ajax from "@/mixins/ajax";

// 我卖出的列表
const getMySellListUrl = "/card-service-web/resell/mySell";
// 修改当前商品价格
const setCurrentPriceUrl = "/card-service-web/resell/updateSellPrice";
// 关闭订单
const setCloseBuyUrl = "/card-service-web/resell/closeBuy";
// 我卖出的记录新街口
const getRecordByCondition = "/card-service-web/resell/getRecordByCondition";
// 筛选列表
const filters = [
  {
    name: "全部",
    status: 0,
    alias: "all"
  },
  {
    name: "待付款",
    status: 1,
    num: 0,
    alias: "payment"
  },
  {
    name: "待发货",
    status: 4,
    num: 0,
    alias: "sendGoods"
  },
  {
    name: "待收货",
    status: 5,
    num: 0,
    alias: "stayGoods"
  },
  {
    name: "已完成",
    status: 7,
    alias: "completed"
  },
  {
    name: "已关闭",
    status: 3,
    alias: "close"
  }
];

export default {
  name: "MySell",
  mixins: [Ajax],
  components: {
    Popups,
    CountDown,
    Scroll
  },
  filters: {
    sellStatusFilter(value) {
      let state = "";
      switch (+value) {
        case 1:
          state = "待买家付款";
          break;
        case 2:
          state = "已取消";
          break;
        case 3:
          state = "已关闭";
          break;
        case 4:
          state = "待平台发货";
          break;
        case 5:
          state = "待买家收货";
          break;
        case 7:
          state = "已完成";
          break;
        default:
          break;
      }
      return state;
    }
  },
  data() {
    return {
      busy: false,
      // 关闭交易窗口控制
      isPopup_cancel: false,
      // 编辑价格窗口控制
      isPopup_edit: false,
      // 我卖出的列表
      mySellList: {},
      // 当前买到的列表
      currentSellList: [],
      // 编辑当前价格
      sellPrice: 0,
      // 当前商品买家ID
      buyUserId: 0,
      // 当前商品卖家ID
      mallResellId: 0,
      // 当前商品转卖订单ID
      mallSellOrderId: 0,
      endTime: "",
      // 空列表？
      emptyList: false,
      // 筛选列表
      filterList: filters,
      // 当前筛选状态
      currentFilterStatus: 0,
      // 当前筛选状态的别名
      currentFilterStatusAlias: "all"
    };
  },
  mounted() {
    // 第一次请求
    this.firstAjax = true;
    this.getMySellList();
    // 更新IScroll尺寸
    // 针对单个页面的宽高设置并更新IScroll
    this.$nextTick(() => {
      // 获取头部筛选列表高度
      const tabListHeight =
        parseInt(this.getStyle(this.$refs.tabList, "height"), 10) + 1;
      // 设置头部筛选列表盒子的高度
      this.$refs.tabScroll.$el.style.height = `${tabListHeight}px`;
      // 计算内容高度
      const mainHeight =
        this.windowHeight - (this.headerElHeight + tabListHeight);
      filters.forEach(item => {
        this.$refs[
          `scroll_${item.alias}`
        ][0].$el.style.height = `${mainHeight}px`;
      });

      this.$refs.tabScroll.refresh();
    });
  },

  methods: {
    /**
     * 倒计时结束则刷新当前商品状态
     */
    handleCountDownEnd(item) {
      /* eslint-disable */
      // 倒计时结束更新徽章
      this.filterList.forEach((key, index) => {
        if (key.status === item.orderStatus) {
          --this.filterList[index].num;
        }
        if (key.status === item.orderStatus) {
          --this.filterList[index].num;
        }
        if (key.status === item.orderStatus) {
          --this.filterList[index].num ;
        }
      });
      // 更新列表
      this.getMySellList();
      // 如果当前商品收货时间结束则改变状态为已完成
      // +item.orderStatus === 5 && (item.orderStatus = 7);
      // 如果当前商品付款时间结束则干煸状态为已关闭
      // +item.orderStatus === 1 && (item.orderStatus = 3);
    },
    // 关闭所有信息框
    closePopAll() {
      this.isPopup_edit = false;
      this.isPopup_cancel = false;
    },
    /**
     * 获取卖出的列表
     */
    getMySellList(status) {
      const url =
        this.currentFilterStatusAlias === "all"
          ? getMySellListUrl
          : getRecordByCondition;
      ((state, currentFilterStatusAlias) => {
        this.post(url, {
          /* eslint-disable */
          pageNo: ++this.currentPageNo,
          pageSize: 10,
          // 当前查询的商品状态
          orderStatus: status,
          // 固定值 1：我买到的 2： 我发布的
          condition: 2
        }).then(body => {
          // 如果当前页为空则设置页码为上一页
          if (body.execDatas.length === 0) {
            --this.currentPageNo;
          }

          if (this.currentPageNo <= 1) {
            // this.mySellList[currentFilterStatusAlias] = body.execDatas;
            this.currentSellList = body.execDatas;
          } else {
            // this.mySellList[currentFilterStatusAlias] = (
            //   this.mySellList[currentFilterStatusAlias] || []
            // ).concat(body.execDatas);
            this.currentSellList = (this.currentSellList || []).concat(
              body.execDatas
            );
          }

          // 如果调用的是全部的接口则更新徽章数据
          if (currentFilterStatusAlias === "all") {
            // 更新徽章数量
            const { waitPayCount, waitPushCount, waitReceivingCount } =
              body.execData || {};
            // 如果是第一次请求
            if (this.firstAjax) {
              this.firstAjax = false;
              // 当前过滤item
              let filter;
              // 如果待付款列表有数据则切换为待付款
              if (waitPayCount > 0) {
                filter = this.filterList.filter(item => {
                  return item.status === 1;
                });
              } else if (waitPushCount > 0) {
                // 如果待付款列表没有数据待发货列表有数据则切换为待发货
                filter = this.filterList.filter(item => {
                  return item.status === 4;
                });
              } else if (waitPushCount > 0) {
                // 如果待付款、待发货列表没有数据待收货列表有数据则切换为待收货
                filter = this.filterList.filter(item => {
                  return item.status === 5;
                });
              }
              // 切换为当前筛选
              filter && this.selectFilter(filter[0]);
            }
            this.filterList.forEach((item, index) => {
              if (waitPayCount > 0 && item.status === 1) {
                this.filterList[index].num = waitPayCount;
              }
              if (waitPushCount > 0 && item.status === 4) {
                this.filterList[index].num = waitPushCount;
              }
              if (waitReceivingCount > 0 && item.status === 5) {
                this.filterList[index].num = waitReceivingCount;
              }
            });
          }
          // 更新IScroll尺寸
          this.$nextTick(() => {
            this.$refs[`scroll_${currentFilterStatusAlias}`][0].refresh();
          });
          if ((this.currentSellList || []).length === 0) {
            this.emptyList = true;
          } else {
            this.emptyList = false;
          }
        });
      })(status || this.currentFilterStatus, this.currentFilterStatusAlias);
    },
    /**
     * 处理关闭交易按钮点击
     */
    handleCloseDeal(item) {
      // 暂存当前转卖订单ID
      this.mallSellOrderId = item.mallSellOrderId;
      // 暂存当前买家ID
      this.buyUserId = item.buyUserId;

      this.isPopup_cancel = !this.isPopup_cancel;
    },
    /**
     * 确定关闭交易
     */
    handleEnsureClose() {
      const { mallSellOrderId, buyUserId } = this;
      this.post(setCloseBuyUrl, {
        id: mallSellOrderId,
        buyUserId: buyUserId
      }).then(body => {
        if (+body.execErrCode === 200) {
          this.currentPageNo = 0;
          this.getMySellList();
          // 当前筛选数量-1
          this.filterList.forEach((item, index) => {
            if (item.alias === this.currentFilterStatusAlias) {
              --this.filterList[index].num;
            }
          });
          this.isPopup_cancel = false;
        }
      });
    },
    /**
     * 处理编辑价格按钮点击
     * @param {Object} item 商品信息
     */
    handleEdit(item) {
      // 暂存当前选择转卖价格
      this.sellPrice = item.sellPrice;
      // 暂存当前选择转卖ID
      this.mallResellId = item.mallResellId;

      this.isPopup_edit = !this.isPopup_edit;
    },
    /**
     * 修改价格
     */
    handelSetPrice() {
      const { mallResellId, sellPrice } = this;
      this.post(setCurrentPriceUrl, {
        mallResellId: mallResellId,
        sellPrice: sellPrice
      }).then(body => {
        this.isPopup_edit = false;
        // 初始化当前页码
        this.currentPageNo = 0;
        // 更新列表
        this.getMySellList();
      });
    },
    /**
     * 选择筛选对象
     */
    selectFilter(filter) {
      // 初始化当前页码
      this.currentPageNo = 0;
      // 保存当前的条件状态码
      this.currentFilterStatus = filter.status;
      // 保存当前条件别名
      this.currentFilterStatusAlias = filter.alias;
      // 更新IScroll尺寸
      this.$nextTick(() => {
        this.$refs[`scroll_${filter.alias}`][0].refresh();
      });
      // 获取数据
      this.getMySellList(filter.status);
    }
  }
};
</script>

<style scoped>
.noList {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 2.6rem;
  right: 0;
  bottom: 0;
  left: 0;
  display: flex;
  justify-content: center;
  padding-top: 3rem;
  color: #888888;
}
.tab {
  height: 1.1rem;
}
.sell-box {
  width: auto;
  background: #fff;
}
.release-list {
  background: #f5f5f4;
}
.tab-list {
  display: flex;
  flex-direction: row;
  align-items: center;
  flex-wrap: nowrap;
  background: #fff;
  font-size: 0.45rem;
  box-shadow: 0rem 0.01rem 0rem 0rem #e1e1e1;
  padding: 0 0.6rem;
  color: #666;
  border-bottom: 0.01rem solid #e1e1e1;
}
.tab-list .tab-item:first-child {
  margin-left: 0;
}
.tab-list .tab-item {
  display: inline-block;
  white-space: nowrap;
  margin-left: 0.8rem;
  padding: 0.26rem 0 0.29rem;
  position: relative;
}
.tab-list .tab-item.active {
  color: #d11463;
  border-bottom: 0.06rem solid #d11463;
}
.tab-list .badge {
  display: inline-block;
  position: absolute;
  top: 0.1rem;
  right: -0.4rem;
  background-color: #d11463;
  font-size: 0.33rem;
  color: #fff;
  min-width: 0.25rem;
  padding: 0.05rem 0.09rem;
  font-weight: 700;
  line-height: 1;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  border-radius: 200px;
}

.release-item {
  background-color: #fff;
  margin-bottom: 0.45rem;
}
.release-item .item-tit {
  display: -webkit-flex;
  display: flex;
  -webkit-flex-direction: row;
  flex-direction: row;
  -webkit-flex-wrap: wrap;
  flex-wrap: wrap;
  padding: 0.46rem 0 0.45rem;
}
.release-item .pic {
  width: 1.8rem;
  height: 1.8rem;
  margin-left: 0.47rem;
  margin-right: 0.2rem;
  background-color: #8e8e8e;
  overflow: hidden;
}
.release-item .pic .picItem {
  width: 1.8rem;
  height: 1.8rem;
}
.goods-info .title {
  margin-bottom: 0.33rem;
  font-size: 0.42rem;
  color: #000000;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 6rem;
}
.goods-info .money {
  font-size: 0.42rem;
  margin-bottom: 0.35rem;
  line-height: 0.36rem;
  letter-spacing: 0rem;
  color: #000000;
}
.goods-info .state {
  display: -webkit-flex;
  display: flex;
  -webkit-flex-direction: row;
  flex-direction: row;
  -webkit-justify-content: space-between;
  justify-content: space-between;
  font-size: 0.36rem;
  line-height: 0.36rem;
  letter-spacing: 0rem;
  color: #d11463;
}
.item-tit .arrow {
  -webkit-align-self: center;
  align-self: center;
  text-align: right;
  margin-right: 0.3rem;
}
.goods-info {
  -webkit-flex-grow: 1;
  flex-grow: 1;
  padding: 0 0.2rem;
}
.item-tit .arrow .icon-arrow {
  display: inline-block;
  width: 0.24rem;
  height: 0.43rem;
  background: url("../../assets/img/arrow.png") no-repeat;
  background-size: 100%;
}
.edit {
  display: -webkit-flex;
  display: flex;
  -webkit-flex-direction: row-reverse;
  flex-direction: row-reverse;
  height: 1.5rem;
  -webkit-align-items: center;
  align-items: center;
  padding-right: 0.48rem;
  border-top: 0.01rem solid #e1e1e1;
}
.edit .edit-btn {
  width: 2.19rem;
  height: 0.9rem;
  background-color: #ffffff;
  border: solid 1px #000000;
  border-radius: 0.1rem;
}
.edit .edit-btn:last-child {
  margin-right: 0.6rem;
}

.form-item {
  height: 1rem;
  display: -webkit-flex;
  display: flex;
  -webkit-flex-direction: row;
  flex-direction: row;
  -webkit-justify-content: space-between;
  justify-content: space-between;
  -webkit-align-items: center;
  align-items: center;
  border-bottom: 0.01rem solid #e1e1e1;
  padding-top: 0.2rem;
  font-size: 0.42rem;
}
.form-item .form-input {
  padding: 0.2rem 0;
  text-align: right;
  max-width: 3.7rem;
  font-size: 0.42rem;
  background: none;
  border: none;
}
input:focus {
  outline: none;
}
/* 弹框按钮公共部分 */
.cancel-info {
  margin-top: 0.63rem;
  font-size: 0.42rem;
}
.pop-footer-btns {
  display: -webkit-flex;
  display: flex;
  -webkit-flex-direction: row;
  flex-direction: row;
  -webkit-justify-content: space-around;
  justify-content: space-around;
}
.pop-footer-cancel {
  width: 2.71rem;
  height: 1.08rem;
  background-color: #5062a6;
  border-radius: 2rem;
  color: #fff;
  font-size: 0.54rem;
}
.pop-footer-sub {
  width: 2.71rem;
  height: 1.08rem;
  background-color: #d11463;
  border-radius: 2rem;
  color: #fff;
  font-size: 0.54rem;
}
.edit-sub {
  width: 5.01rem;
  height: 1.08rem;
  background-color: #d11463;
  border-radius: 2rem;
  font-size: 0.54rem;
  color: #fff;
}
</style>

